<template>
  <bc-container>
    <data-panel ref="dataPanelRef" :columns="columns" :dataSource="tableData" :otherQuery="otherQuery">
      <template #action="{ scope }">
        <div class="handle-box">
          <el-button link type="primary" @click="handleEditOrDetail('edit', scope.row)"> 跟进记录 </el-button>
          <el-button link type="primary" @click="handleDel(scope.row)"> 删除 </el-button>
        </div>
      </template>
    </data-panel>
  </bc-container>
  <bc-modal :size="720" type="drawer" title="跟进记录" v-model="dialogVisible" footer>
    <div class="card">
      <el-timeline style="max-width: 600px">
        <el-timeline-item
          v-for="(activity, index) in activities"
          :key="index"
          :timestamp="activity.timestamp"
          :type="activity.type"
        >
          {{ activity.content }}
        </el-timeline-item>
      </el-timeline>
    </div>
    <el-form ref="ruleFormRef" label-position="right" :model="formData" label-width="auto">
      <bc-form ref="bcFormRef" :border="false" :fields="formOptions" :cols="1" :mode="mode" @change="handleChange">
      </bc-form>
    </el-form>
    <template #footer>
      <el-button @click="onClose">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </template>
  </bc-modal>
</template>

<script setup>
import DataPanel from '@/components/DataPanel.vue'
import BcModal from '@/components/BcModal.vue'
import BcForm from '@/components/bcForm/Index.vue'
import { formOptions, columns } from './config'
import { nextTick, reactive, shallowRef, watch } from 'vue'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'
const userStore = useUserStore()

const otherQuery = reactive({
  communityId: userStore.communityId,
})
watch(
  () => userStore.communityId,
  () => {
    otherQuery.communityId = userStore.communityId
  }
)

/**
 * 列表
 */
const dataPanelRef = shallowRef()
const tableData = async (params, other) => {
  params = { ...params, ...other }
  const res = await $request.post('/api-parking/businessOpportunity/query', { params })
  return res
}
const loadData = () => {
  nextTick(() => {
    dataPanelRef.value.load()
  })
}

/**
 * 表单-线索
 */
const mode = ref('edit')
const ruleFormRef = shallowRef()
const bcFormRef = shallowRef()
const dialogVisible = ref(false)
const formData = reactive({})
const activities = reactive([
  { timestamp: '2023-10-01 10:00', content: '商机创建' },
  { timestamp: '2023-10-02 12:30', content: '初步跟进' },
  { timestamp: '2023-10-03 15:45', content: '客户反馈' },
])
const handleChange = (val) => {
  Object.assign(formData, val.value)
}
const onClose = () => {
  dialogVisible.value = false
}
const onOpen = (val) => {
  dialogVisible.value = true
  Object.keys(formData).forEach((key) => {
    delete formData[key]
  })
  Object.assign(formData, val)
  nextTick(() => {
    bcFormRef.value.set(val)
    ruleFormRef.value.resetFields()
  })
}
// 编辑
const handleEditOrDetail = async (val, scope) => {
  const info = { businessOpportunityId: scope.id, followTime: dayjs().valueOf() }
  const params = { businessOpportunityId: scope.id, pageSize: 1000, pageNum: 1 }
  const res = await $request.post('/api-parking/followRecord/list', { params })
  activities.splice(
    0,
    activities.length,
    ...res.rows.map((item) => ({
      timestamp: dayjs(item.followTime).format('YYYY-MM-DD HH:mm'),
      content: `${item.followContent || ''} 「${item.followerName || ''}」`,
      type: item.followStatus == 1 ? 'info' : item.followStatus === 2 ? 'success' : 'warning',
    }))
  )
  mode.value = val
  onOpen(info)
}
// 提交
const handleSubmit = async () => {
  try {
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        const params = { ...formData }
        await $request.post('/api-parking/followRecord/add', { params })
        onClose()
        ElMessage({
          type: 'success',
          message: '操作成功',
        })
        // 刷新表单
        loadData()
      }
      return false
    })
  } catch (error) {
    return Promise.reject(error)
  }
}

//  ---- 删除 ----
const handleDel = (info) => {
  const { id } = info
  ElMessageBox.confirm(`是否删除该商机?`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      // 执行删除操作
      await $request.delete(`/api-parking/businessOpportunity/${id}`)
      // 显示成功消息
      ElMessage({
        type: 'success',
        message: '操作成功',
      })
      // 刷新表单
      loadData()
    })
    .catch(() => {
      // 显示取消消息
    })
}
</script>

<style lang="scss" scoped>
.card {
  height: calc(100vh - 285px);
  overflow-y: auto;
  background: #fff;
  padding: 20px;
  margin-bottom: 12px;
  border-radius: 4px;
}
</style>
